import { defineStore } from "pinia";
import {
	getToken,
	setToken,
	removeToken,
	getCode,
	setCode,
	removeCode,
} from "~/utils/auth";
import { store } from "~/store/index";
import { useLayoutStore } from "./layout";
import router from "~/router";
interface UserInfo {
	userName: string;
	fullName: string;
	accountStatus: string;
	createTime: string;
	idCard: string;
	id: string;
	mobileNumber: string;
	loginType: string;
}
interface UserState {
	token: string | null;
	code: string;
	userInfo: UserInfo;
}

export const useUserStore = defineStore({
	id: "land-user",
	state: (): UserState => ({
		token: getToken(),
		code: getCode(),
		userInfo: {
			userName: "",
			fullName: "",
			accountStatus: "",
			createTime: "",
			idCard: "",
			id: "",
			mobileNumber: "",
			loginType: "",
		},
	}),
	persist: {
		enabled: true,
		// 自定义持久化参数
		strategies: [
			{
				// 自定义key
				key: "user_store",
				// 自定义存储方式，默认sessionStorage
				storage: localStorage,
				// 指定要持久化的数据，默认所有 state 都会进行缓存，可以通过 paths 指定要持久化的字段，其他的则不会进行持久化。
				paths: ["token", "code"],
			},
		],
	},
	actions: {
		setStateToken(token) {
			this.token = token;
			setToken(token);
		},
		setStateCode(code) {
			this.code = code;
			setCode(code);
		},
		resetStateToken() {
			const layoutStore = useLayoutStore();
			return new Promise<void>((resolve) => {
				this.token = "";
				this.code = "";
				layoutStore.setRolesMenu([]);
				layoutStore.delAllTag();
				layoutStore.setRolesLeftMenu({});
				removeToken();
				removeCode();
				resolve();
			});
		},
		getUserInfo() {
			
		},
		login(formData) {
			
		},
		singOut() {
			
		},
		zzdSetToken(data) {
			this.setStateToken(data.token);
			this.setStateCode(data.authCode);
		},
		updateUserInfo(newUserInfo) {
			
		},
	},
	getters: {},
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
	return useUserStore(store);
}
